<?php
require_once '../config.php'; 
require_once '../admin_check.php';

$errors = [];
$form_data = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 接收并清理表单数据
    $username = clean_input($_POST['username'] ?? '');
    $email = clean_input($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $role = $_POST['role'] ?? 'user';
    $security_question = clean_input($_POST['security_question'] ?? '');
    $security_answer = clean_input($_POST['security_answer'] ?? '');

    // 处理自定义安全问题
    if ($security_question === '自定义问题') {
        $security_question = clean_input($_POST['custom_question'] ?? '');
        
        // 添加自定义问题验证
        if (empty($security_question)) {
            $errors[] = '自定义安全问题不能为空';
        } elseif (strlen($security_question) < 5) {
            $errors[] = '自定义安全问题至少需要5个字符';
        }
    }

    // 数据验证
    if (empty($username)) {
        $errors[] = '用户名不能为空';
    }
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = '邮箱格式无效';
    }
    // 密码复杂度验证
    if (!preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/', $password)) {
        $errors[] = '密码必须包含大小写字母和数字，且至少8个字符';
    }
    if ($password !== $confirm_password) {
        $errors[] = '两次输入的密码不一致';
    }
    if (!in_array($role, ['user', 'admin'])) {
        $errors[] = '无效的用户角色';
    }
    // 安全问题和答案验证（预定义问题）
    if ($security_question !== '自定义问题' && (empty($security_question) || strlen($security_question) < 5)) {
        $errors[] = '安全问题至少需要5个字符';
    }
    if (empty($security_answer) || strlen($security_answer) < 2) {
        $errors[] = '安全答案至少需要2个字符';
    }

    // 检查用户名和邮箱唯一性
    $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
    $stmt->execute([$username, $email]);
    if ($stmt->rowCount() > 0) {
        $errors[] = '用户名或邮箱已被使用';
    }

    if (empty($errors)) {
        try {
            $pdo->beginTransaction();

            // 哈希处理密码和答案
            $password_hash = password_hash($password, PASSWORD_DEFAULT);
            $answer_hash = password_hash(
                mb_strtolower(trim($security_answer)), 
                PASSWORD_DEFAULT
            );

            // 插入用户数据
            $stmt = $pdo->prepare("INSERT INTO users 
                (username, email, password, role, security_question, security_answer_hash)
                VALUES (?, ?, ?, ?, ?, ?)");
            
            $stmt->execute([
                $username,
                $email,
                $password_hash,
                $role,
                $security_question,
                $answer_hash
            ]);

            $pdo->commit();
            $_SESSION['success'] = '用户添加成功';
            header('Location: index.php');
            exit;
        } catch (PDOException $e) {
            $pdo->rollBack();
            $errors[] = '添加用户失败：' . $e->getMessage();
        }
    }

    // 保存已填数据用于回显
    $form_data = [
        'username' => $username,
        'email' => $email,
        'role' => $role,
        'security_question' => $_POST['security_question'] ?? '',
        'custom_question' => $_POST['custom_question'] ?? '',
        'security_answer' => $security_answer
    ];
}

include '../includes/header.php';
?>

<div class="container mt-4">
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h4>新增用户</h4>
            <a href="index.php" class="btn btn-secondary">返回列表</a>
        </div>
        <div class="card-body">
            <form method="post">
                <div class="row g-3">
                    <!-- 基础信息 -->
                    <div class="col-md-6">
                        <label class="form-label">用户名</label>
                        <input type="text" class="form-control" name="username" 
                               value="<?= htmlspecialchars($form_data['username'] ?? '') ?>" required>
                    </div>
                    
                    <div class="col-md-6">
                        <label class="form-label">电子邮箱</label>
                        <input type="email" class="form-control" name="email" 
                               value="<?= htmlspecialchars($form_data['email'] ?? '') ?>" required>
                    </div>

                    <!-- 密码字段 -->
                    <div class="col-md-6 position-relative">
                        <label class="form-label">密码</label>
                        <div class="input-group">
                            <input type="password" 
                                   class="form-control" 
                                   name="password"
                                   id="passwordInput"
                                   required
                                   value="<?= htmlspecialchars($_POST['password'] ?? '') ?>"
                                   pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
                                   title="必须包含大小写字母和数字"
                                   data-bs-toggle="popover"
                                   data-bs-custom-class="password-popover custom-popover"
                                   data-bs-placement="auto"
                                   data-bs-trigger="focus"
                                   data-bs-html="true"
                                   data-bs-title="密码要求"
                                   data-bs-content="<ul class='list-unstyled mb-0'>
                                       <li id='popover-length' class='text-danger'><i class='bi bi-x-circle-fill'></i> 至少8个字符</li>
                                       <li id='popover-lowercase' class='text-danger'><i class='bi bi-x-circle-fill'></i> 包含小写字母</li>
                                       <li id='popover-uppercase' class='text-danger'><i class='bi bi-x-circle-fill'></i> 包含大写字母</li>
                                       <li id='popover-number' class='text-danger'><i class='bi bi-x-circle-fill'></i> 包含数字</li>
                                   </ul>">
                            <button type="button" class="btn btn-outline-secondary toggle-password">
                                <i class="bi bi-eye"></i>
                            </button>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">确认密码</label>
                        <div class="input-group">
                            <input type="password" class="form-control" name="confirm_password" required>
                            <button type="button" class="btn btn-outline-secondary toggle-password">
                                <i class="bi bi-eye"></i>
                            </button>
                        </div>
                    </div>

                    <!-- 角色选择 -->
                    <div class="col-md-6">
                        <label class="form-label">用户角色</label>
                        <select class="form-select" name="role" required>
                            <option value="user" <?= ($form_data['role'] ?? '') === 'user' ? 'selected' : '' ?>>普通用户</option>
                            <option value="admin" <?= ($form_data['role'] ?? '') === 'admin' ? 'selected' : '' ?>>管理员</option>
                        </select>
                    </div>

                    <!-- 安全设置 -->
                    <div class="col-md-6">
                        <label class="form-label">密保问题</label>
                        <select class="form-select" name="security_question" id="securityQuestion" required>
                            <option value="">请选择安全问题</option>
                            <option value="您母亲的名字是什么？" <?= ($form_data['security_question'] ?? '') === '您母亲的名字是什么？' ? 'selected' : '' ?>>您母亲的名字是什么？</option>
                            <option value="您的出生城市是哪里？" <?= ($form_data['security_question'] ?? '') === '您的出生城市是哪里？' ? 'selected' : '' ?>>您的出生城市是哪里？</option>
                            <option value="您的第一所学校的名称是？" <?= ($form_data['security_question'] ?? '') === '您的第一所学校的名称是？' ? 'selected' : '' ?>>您的第一所学校的名称是？</option>
                            <option value="自定义问题" <?= ($form_data['security_question'] ?? '') === '自定义问题' ? 'selected' : '' ?>>自定义问题...</option>
                        </select>
                    </div>

                    <div class="col-md-6" id="customQuestionContainer" style="display: <?= ($form_data['security_question'] ?? '') === '自定义问题' ? 'block' : 'none' ?>;">
                        <label class="form-label">自定义安全问题</label>
                        <input type="text" class="form-control" name="custom_question"
                               value="<?= htmlspecialchars($form_data['custom_question'] ?? '') ?>"
                               placeholder="请输入自定义安全问题">
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">安全问题答案</label>
                        <input type="text" class="form-control" name="security_answer"
                               value="<?= htmlspecialchars($form_data['security_answer'] ?? '') ?>" required minlength="2">
                    </div>

                    <div class="col-12">
                        <button type="submit" class="btn btn-primary">添加用户</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include '../includes/footer.php'; ?>